<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="1000px"
    :before-close="close"
    :close-on-click-modal="false"
  >
    <el-scrollbar v-loading="loading" max-height="calc(100vh - 350px)">
      <div style="width: 98%">
        <ApproveRecords
          v-if="detail?.matterSubProcessVos?.length"
          :approveRecords="detail.matterSubProcessVos"
        />
        <el-descriptions :title="detail?.applyTopic">
          <el-descriptions-item label="关联事项：">
            {{ detail?.matterTitle }}
          </el-descriptions-item>
          <el-descriptions-item label="申请部门：">
            {{ detail?.applyUnitName }}
          </el-descriptions-item>
          <el-descriptions-item label="申请人：">
            {{ detail?.applyUserName }}
          </el-descriptions-item>
          <el-descriptions-item label="申请时间：">
            {{ detail?.applyTime }}
          </el-descriptions-item>

          <el-descriptions-item label="协调部门：">
            {{ detail?.coordinationDeptName }}
          </el-descriptions-item>

          <el-descriptions-item label="审批状态：">
            <ApproveShow :status="detail?.applyStatus" />
          </el-descriptions-item>

          <el-descriptions-item :span="3" label="协调内容：">
            {{ detail?.applyReason }}
          </el-descriptions-item>

          <el-descriptions-item :span="3" label="相关材料：">
            <el-row>
              <el-col
                v-for="file of detail?.audioDataVos"
                :key="file.id"
                :span="24"
              >
                <el-link
                  type="primary"
                  :loading="downloadFileLoading"
                  @click="handleDownloadFile(file)"
                >
                  {{ file.orgFileName }}
                </el-link>
              </el-col>
            </el-row>
          </el-descriptions-item>
        </el-descriptions>
        <ApproveForm
          v-if="detailType === EDetailType.APPROVE"
          ref="approveRef"
        />
      </div>
    </el-scrollbar>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <template v-if="detailType === EDetailType.APPROVE">
          <el-button
            type="danger"
            :loading="approveLoading"
            @click="handleApprove(EApproveStatus['不通过'])"
          >
            不通过
          </el-button>
          <el-button
            type="primary"
            :loading="approveLoading"
            @click="handleApprove(EApproveStatus['通过'])"
          >
            通过
          </el-button>
        </template>
      </div>
    </template>
  </el-dialog>
  <SelectApprovePerson
    ref="selectApprovePerson"
    @submit="handleSelectPersonSuccess"
  />
</template>

<script setup lang="ts">
import { computed, ref, useTemplateRef } from 'vue'
import {
  approveCoordinationApplication,
  getCoordinationApplicationDetailById,
  IApproveRequest,
  ICoordinationApplicationDetail,
} from '@/api/application/coordination'
import useFetch from '@/hooks/useFetch'
import { EDetailType } from '../typings'
import ApproveForm from '@/components/approve/ApproveForm.vue'
import { IFileObj } from '@/type/file'
import ApproveRecords from '@/components/approve/ApproveRecords.vue'
import { getFileStreamById } from '@/api/file'
import { downloadFile } from '@/plugins/file'
import SelectApprovePerson from '@/components/approve/SelectApprovePerson.vue'
import { isLastApprovePerson } from '../utils'
import ApproveShow from '@/components/statusShow/approve/ApproveShow.vue'
import { EApproveStatus } from '@/components/statusShow/util'
import { Message } from '@/hooks/message'
import { ESelectApproveUserType } from '@/api/sys/userManage'

const selectApprovePerson = useTemplateRef<typeof SelectApprovePerson>(
  'selectApprovePerson',
)

const approveRef =
  useTemplateRef<InstanceType<typeof ApproveForm>>('approveRef')

const curApproveInfo = ref()

const emits = defineEmits(['update'])

const {
  res: detail,
  loading,
  execute,
} = useFetch<ICoordinationApplicationDetail>(
  getCoordinationApplicationDetailById,
)

const {
  loading: approveLoading,
  execute: approveExecute,
  onFetchSuccess,
} = useFetch(approveCoordinationApplication)

onFetchSuccess(() => {
  close()
  Message({
    message: '审批完成',
    type: 'success',
  })
  emits('update')
})

const {
  loading: downloadFileLoading,
  execute: downloadFileExecute,
  onFetchSuccess: downloadFileOnFetchSuccess,
} = useFetch(getFileStreamById)

downloadFileOnFetchSuccess((data: Blob, fileName: string) => {
  downloadFile(data, fileName)
})

const detailId = ref(0)

const dialogVisible = ref(false)

defineExpose({ show })

const detailType = ref(EDetailType.VIEW)
const title = computed(() => {
  return detailType.value === EDetailType.VIEW ? '协调申请详情' : '协调申请审核'
})

async function show(id?: number, type = EDetailType.VIEW) {
  detailType.value = type
  dialogVisible.value = true
  if (id) {
    detailId.value = id
    await execute(id)
  }
}

function close() {
  dialogVisible.value = false
  if (detailType.value === EDetailType.APPROVE) {
    approveRef.value?.reset()
  }
  curApproveInfo.value = undefined
}

// 审批
async function handleApprove(result: EApproveStatus) {
  await approveRef.value?.validate(async (approveInfo: IApproveRequest) => {
    curApproveInfo.value = approveInfo
    if (result === EApproveStatus['通过']) {
      const isLastPerson = isLastApprovePerson(
        detail?.value?.matterSubProcessVos,
      )
      if (isLastPerson) {
        asyncApprove(result)
      } else {
        selectApprovePerson.value?.show({
          type: ESelectApproveUserType.COORDINATION,
          applyId: detailId.value,
        })
      }
    } else {
      asyncApprove(result)
    }
  })
}

// 异步审批
async function asyncApprove(result: EApproveStatus, processUserId?: number) {
  const postData = {
    applyType: 2,
    processResult: result,
    ...curApproveInfo.value,
    processUserId,
    id: detail.value?.matterSubProcessVos?.[
      detail.value?.matterSubProcessVos?.length - 1
    ]?.id,
  }
  await approveExecute(postData)
}

// 预览文件
async function handleDownloadFile(file: IFileObj) {
  await downloadFileExecute<number, string>(file.id, true, file.orgFileName)
}

// 选择完毕
function handleSelectPersonSuccess(approveUserId: number) {
  asyncApprove(EApproveStatus['通过'], approveUserId)
}
</script>

<style scoped lang="scss">
:deep(.el-date-editor.el-date-editor--date) {
  --el-date-editor-width: 190px;
  margin-right: 16px;
}
</style>
